import axios from 'axios'
import { createBrowserHistory} from 'history'
import { notification } from 'antd'
import store from '../store'

var history = createBrowserHistory()

//实例化
var service = axios.create({
  timeout:10*1000,
  baseURL:process.env.REACT_APP_BASE_API
})

//设置请求拦截器
service.interceptors.request.use(
  (config)=>{
    //设置请求头参数
    config.headers['token'] = store.getState().userInfo.token; 
    return config 
  },
  (err)=>{
    return Promise.reject(err)
  }
)

//设置响应拦截器
service.interceptors.response.use(
  (res)=>{
    if(res.data.code == '10119'){
      notification.error({message:'登录过期，请重新登陆'})
      store.dispatch({type:'REMOVE_USERINFO'})
      history.push('/login')
      history.go(0)
    }
    return res
  },
  (err)=>{
    if(err.response.this.status == 401){
      notification.error({message: '登录过期，请重新登陆'})
      history.push('/login')
      history.go(0)
    }else if(err.response.this.status == 404){
      notification.error({message: '访问路径有误'})
    }else if(err.response.this.status == 500){
      notification.error({message: '服务器内部错误'})
    }else if(err.response.this.status == 503){
      notification.error({message: '服务器无法提供服务'})
    }
    return Promise.reject(err)
  }
)

export default service